import { Button } from 'antd';
import { SubscriptionAPI } from 'dva';
import React, { Fragment, useEffect, useState } from 'react';
import WeChatDoctor, { IGroup } from '../../../api/WeChatDoctor';
import { MobileAddBlockContent, MobileHeader } from '../../../components/index';
import { MobilePagination } from '../../../utils';
import UpdateTitle from '../../../utils/UpdateTitle';
import './DoctorGroup.scss';

interface IDeleteState {
  isDeleting: boolean;
  deleteArr: number[];
}
export default (props: SubscriptionAPI) => {
  const [pagnation, setPagnation] = useState({ pageSize: 10, total: 0, pageNum: 1 });
  const [groups, setGroups] = useState<IGroup[]>([]);
  const [deleteState, setDeleteState] = useState<IDeleteState>({ isDeleting: false, deleteArr: [] });
  const [deleteSuccess, setDeleteSuccess] = useState(false);
  useEffect(() => {
    if (deleteSuccess) {
      getGroups();
      setDeleteSuccess(false);
    }
  }, [deleteSuccess]);
  useEffect(() => {
    getGroups();
    UpdateTitle('我的分组');
  }, []);
  // 滚动加载下一页
  async function scrollEvent() {
    const pageNum = await MobilePagination('groupList', pagnation.pageNum, pagnation.pageSize, pagnation.total);
    if (pageNum) {
      pagnation.pageNum = pageNum;
      getGroups();
    }
  }
  // 单个分组点击事件
  function itemClick(id: number) {
    if (deleteState.isDeleting) {
      let deleteArr = deleteState.deleteArr;
      if (deleteArr.lastIndexOf(id) !== -1) {
        deleteArr = deleteArr.filter(v => {
          return v !== id;
        });
      } else {
        deleteArr.push(id);
      }
      setDeleteState({ ...deleteState, deleteArr });
    } else {
      props.history.push(`/Doctor/DoctorGroupDetail/${id}`);
    }
  }
  // 获取我的分组
  async function getGroups() {
    const searchRequest = {
      pageNum: pagnation.pageNum,
      pageSize: pagnation.pageSize,
    };
    const { result } = await WeChatDoctor.getMyGroups(searchRequest);
    setPagnation({ ...pagnation, total: result.total });
    setGroups([...groups, ...result.records]);
  }
  // 确认删除
  async function deleteSure() {
    if (deleteState.deleteArr.length > 0) {
      const result = await WeChatDoctor.deleteGroup({ data: { ids: deleteState.deleteArr } });
      if (result.code === 0) {
        setDeleteState({ isDeleting: false, deleteArr: [] });
        pagnation.pageNum = 1;
        setGroups([]);
        setDeleteSuccess(true);
      }
    } else {
      setDeleteState({ isDeleting: false, deleteArr: [] });
    }
  }
  let list;
  let imgArea;
  if (groups.length <= 0) {
    list = (
      <div className="noGroup">
        <img src={require('./../../../assets/img/img_group_null.svg')} />
        <p>您还没有分组</p>
      </div>
    );
  } else {
    list = groups.map(v => {
      imgArea = v.hulkUserInfoList.map((item, index) => {
        return <img key={index} src={item.headimgurl} />;
      });
      return (
        <div key={v.id} className="groupItem" onClick={() => itemClick(v.id)}>
          <div className="titleArea">
            {// tslint:disable-next-line:  jsx-no-multiline-js
            deleteState.isDeleting && deleteState.deleteArr.lastIndexOf(v.id!) === -1 ? (
              <img className="deleteIcon" src={require('../../../assets/img/icon_delete_time.svg')} />
            ) : (
              ''
            )}
            {// tslint:disable-next-line: jsx-no-multiline-js
            deleteState.isDeleting && deleteState.deleteArr.lastIndexOf(v.id!) !== -1 ? (
              <img className="deleteIcon" src={require('../../../assets/img/icon_delete_time_select.svg')} />
            ) : (
              ''
            )}
            <p className="title">{v.name}</p>
            <div className="imgArea">{imgArea}</div>
            <p className="number">{v.hulkUserInfoList.length}人</p>
            <img className="detailsArrow" src={require('../../../assets/img/icon_more.svg')} />
          </div>
          <div className="contentDes">{v.description}</div>
        </div>
      );
    });
  }
  return (
    <div id="Doctor-DoctorGroup">
      {/* <NavBar mode="light" leftContent={[<img src={require('./../../../assets/img/btn_back.svg')} />, '返回']}></NavBar> */}
      <div className="contentArea">
        <MobileHeader backUrl={'/Doctor/DoctorInfo'}>
          {// tslint:disable-next-line: jsx-no-multiline-js
          deleteState.isDeleting ? (
            <Fragment>
              <Button type={'link'} onClick={() => setDeleteState({ isDeleting: false, deleteArr: [] })}>
                取消
              </Button>
              <Button type={'link'} className="deleteSure" onClick={deleteSure}>
                确定删除
              </Button>
            </Fragment>
          ) : (
            <Button
              type={'link'}
              disabled={groups.length === 0}
              onClick={() => setDeleteState({ ...deleteState, isDeleting: true })}
            >
              删除组
            </Button>
          )}
        </MobileHeader>

        <MobileAddBlockContent backUrl={`/Doctor/DoctorAddGroup/ADD/0`}>添加分组</MobileAddBlockContent>

        <div className="groupList" id="groupList" onScroll={scrollEvent}>
          {list}
        </div>
      </div>
    </div>
  );
};
